package com.dj.product.k2faas.service.function;

import com.dj.product.k2faas.dto.function.*;
import com.dj.product.k2faas.entity.function.Function;
import com.dj.product.k2faas.common.utils.BeanUtil;
import com.dj.product.k2faas.view.function.FunctionView;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

/**
 * Created by 丁建 on 2025/9/23 16:36
 *
 * @author 丁建
 */
@Transactional
@Service
public class DefaultFunctionService implements FunctionService {

    @Autowired
    private FunctionView functionView;

    @Override
    public long add(CreateFunctionRequest function) {
        var fct = BeanUtil.convert(function, Function.class).setStatus(Function.FunctionStatus.未运行);
        return functionView.save(fct).getId();
    }

    @Override
    public void edit(UpdateFunctionRequest function) {
        var fct = functionView.findById(function.getId());
        functionView.save(fct);
    }

    @Override
    public FunctionResponse findById(long id) {
        var fct = functionView.findById(id);
        return BeanUtil.convert(fct, FunctionResponse.class);
    }

    @Override
    public Page<FunctionResponse> findAll(String keyword, Pageable pageable) {
        var pageInfo = functionView.findAll(keyword, pageable);
        return BeanUtil.toPage(pageInfo, FunctionResponse.class, pageable);
    }

    @Override
    public TestFunctionResponse testFunction(TestFunctionRequest request) {
        throw new RuntimeException("尚未开发");
    }

    @Override
    public void disable(long id) {
        var fct = functionView.findById(id).setStatus(Function.FunctionStatus.禁用);
        functionView.save(fct);
    }

    @Override
    public void start(long id) {
        var fct = functionView.findById(id).setStatus(Function.FunctionStatus.运行中);
        functionView.save(fct);
    }

    @Override
    public void stop(long id) {
        var fct = functionView.findById(id).setStatus(Function.FunctionStatus.未运行);
        functionView.save(fct);
    }
}
